package cn.glenn._04weibo.controller;

import cn.glenn._04weibo.base.response.JsonResult;
import cn.glenn._04weibo.mapper.WeiboMapper;
import cn.glenn._04weibo.pojo.enity.Weibo;
import cn.glenn._04weibo.pojo.vo.UserVO;
import cn.glenn._04weibo.pojo.vo.WeiboDetailVO;
import cn.glenn._04weibo.pojo.vo.WeiboIndexVO;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;


    @PostMapping("insert")
    public JsonResult postWeibo(@RequestBody String content, HttpSession session) {
        if ((session.getAttribute("user"))==null) {return JsonResult.notLogin();}
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.debug("userVO:{}",userVO);
        Weibo weibo = new Weibo();
        weibo.setContent(content);
        weibo.setUserId(userVO.getId());
        weibo.setCreated(new Date());
        log.debug("weibo:{}",weibo);
        int result = weiboMapper.insert(weibo);
        log.debug("result:{}",result);
        return JsonResult.success();
    }

    @GetMapping("selectIndex")
    public JsonResult selectWeiboIndex(HttpSession session) {
        if ((session.getAttribute("user"))==null) {return JsonResult.notLogin();}
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.debug("userVO:{}",userVO);
        List<WeiboIndexVO> weiboIndexVOList = weiboMapper.selectWeiboByUserId((long)userVO.getId());
        log.debug("weiboIndexVOList:{}",weiboIndexVOList);
        return JsonResult.success(weiboIndexVOList);
    }

    @GetMapping("selectById")
    public JsonResult weiboDetail(@Valid @Range(min = 200,max = 500,message = "编号必须在200-500之间") Long id) {
        WeiboDetailVO weiboDetailVO = weiboMapper.selectWeiboDetailById(id);
        log.debug("weiboDetailVO:{}",weiboDetailVO);
        return JsonResult.success(weiboDetailVO);
    }
}
